<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogFormVisible"
    width="500px"
    @close="close"
  >
    <el-form ref="form" label-width="40px" :model="form">
      <el-form-item>
        <el-checkbox-group v-model="form.roles">
          <el-checkbox
            v-for="(item, index) in roles"
            :key="index"
            :label="item.id"
          >
            {{ item.title }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script>
  import { doRole } from '@/api/authUser'
  import { getList } from '@/api/authRole'

  export default {
    name: 'Edit',
    data() {
      return {
        form: {
          roles: [],
        },
        title: '',
        dialogFormVisible: false,
        id: '',
        roles: [],
      }
    },
    methods: {
      showRole(row) {
        this.title = '关联角色'
        this.id = row.id
        this.getList()
        this.form.roles = row.roles.map((val) => val.id)
        this.dialogFormVisible = true
      },
      close() {
        this.$refs['form'].resetFields()
        this.form = this.$options.data().form
        this.dialogFormVisible = false
      },
      save() {
        // 具体业务请自行调整
        this.$refs['form'].validate(async (valid) => {
          if (valid) {
            this.doRole(this.id, this.form.roles)
            this.$emit('fetch-data')
            this.close()
          }
        })
      },
      async doRole(roleId, roles) {
        const { msg } = await doRole(roleId, roles)
        this.$baseMessage(msg, 'success', 'vab-hey-message-success')
      },
      async getList() {
        const {
          data: { data },
        } = await getList({ pagesize: 100 })
        this.roles = data
      },
    },
  }
</script>

<style lang="scss" scoped></style>
